const bookDataKey = 'localBookData'

/**
 * 查询
 * @returns {*[]}
 */
export const getBookDataList = () => {
    let storedData = localStorage.getItem(bookDataKey)
    console.log("sj", storedData)
    let trueData
    if (storedData === null || storedData === 'undefined') {
        trueData = []
        localStorage.setItem(bookDataKey, JSON.stringify(trueData));
    } else {
        trueData = JSON.parse(storedData)
    }
    return trueData
}

/**
 * 保存
 * @param bookList
 * @returns {boolean}
 */
export const saveBookList = (bookList) => {
    if (Array.isArray(bookList)) {
        localStorage.setItem(bookDataKey, JSON.stringify(bookList));
        return true
    } else {
        return false
    }
}

/**
 * 保存一本书
 * @param bookItem
 */
export const saveBookItem = (bookItem) => {
    const bookList = getBookDataList()
    let maxId = 0;
    bookList.forEach(item => {
        if (maxId < item.id) {
            maxId = item.id
        }
    })
    bookItem.id = maxId + 1
    bookList.push(bookItem)
    localStorage.setItem(bookDataKey, JSON.stringify(bookList));
}

/**
 * 根据id删除一本书
 * @param bookItemId
 */
export const deleteBook = (bookItemId) => {
    const bookList = getBookDataList()
    const newBookList = bookList.filter((item) => item.id !== bookItemId)
    localStorage.setItem(bookDataKey, JSON.stringify(newBookList));
}

export const updateBook = (bookItem) => {
    const bookDataList = getBookDataList()
    bookDataList.forEach(item => {
        if (item.id === bookItem.id) {
            console.log("找到了")
            item.bookName = bookItem.bookName
            item.author = bookItem.author
            item.number = bookItem.number
            item.press = bookItem.press
        }
    })
    localStorage.setItem(bookDataKey, JSON.stringify(bookDataList));
}

